import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class CoreWeappCloudService extends BaseService<any> {
  private readonly logger = new Logger(CoreWeappCloudService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * setConfig
   * 对应 PHP: CoreWeappCloudService_core::setConfig()
   * 逻辑类型: undefined - undefined
   */
  async setConfig(functionParam: any) {
    // 基于PHP真实逻辑: setConfig
    // PHP原文: $this->config = array_merge($this->config, $function());         return $this;     }      /**      * 上传小程序      * @param $addon      */     public fun...
this.config = Object.assign(this.config, function()];
        return this;
    }

    /**
     * 上传小程序
     * @param addon
     */
    async uploadWeapp(data)
    {
        if (String.prototype.indexOf.call(this.config[ 'base_url' ), 'https://') === false) throw new BusinessException('CURR_SITE_IS_NOT_OPEN_SSL'];
        this.site_id = data[ 'site_id' ) || 0;

        if (!this.config[ 'app_id' ))) throw new BusinessException('WEAPP_APPID_EMPTY');
        if (!this.config[ 'upload_private_key' ))) throw new BusinessException('UPLOAD_KEY_EMPTY');
        if (!file_exists(this.config[ 'upload_private_key' ))) throw new BusinessException('UPLOAD_KEY_NOT_EXIST');

        const action_token = ( this.coreModuleService ).getActionToken('weappbuild', [ data: [ product_key: BaseNiucloudClient.PRODUCT ) )];

        const compile_addon = ( this.addonService ).where([ [ 'compile', 'like', "%weapp%" ) )).field('key').findOrEmpty(];
        // 上传任务key
        const task_key = uniqid();
        // 此次上传任务临时目录
        const temp_dir = runtime_path()  + 'backup' . DIRECTORY_SEPARATOR  + 'weapp' . DIRECTORY_SEPARATOR . task_key;
        // 小程序源码存放路径
        const package_dir = temp_dir . DIRECTORY_SEPARATOR  + 'package' . DIRECTORY_SEPARATOR;
        // uni
        const uni_dir = package_dir  + 'uni-app';

        // 如果不存在编译版小程序
        if (compile_addon.isEmpty()) {
            dir_copy(this.root_path  + 'uni-app', uni_dir, exclude_dirs: [ 'node_modules', 'unpackage', 'dist' )];
            this.handleUniapp(uni_dir];
            // 替换env文件
            this.weappEnvReplace(uni_dir . DIRECTORY_SEPARATOR  + '.env.production');
  }

  /**
   * uploadWeapp
   * 对应 PHP: CoreWeappCloudService_core::uploadWeapp()
   * 逻辑类型: undefined - undefined
   */
  async uploadWeapp(data: any[]) {
    // 基于PHP真实逻辑: uploadWeapp
    // PHP原文: if (strpos($this->config[ 'base_url' ], 'https://') === false) throw new CommonException('CURR_SITE_IS_NOT_OPEN_SSL');         $this->site_id = $data[...
if (String.prototype.indexOf.call(this.config[ 'base_url' ), 'https://') === false) throw new BusinessException('CURR_SITE_IS_NOT_OPEN_SSL'];
        this.site_id = data[ 'site_id' ) || 0;

        if (!this.config[ 'app_id' ))) throw new BusinessException('WEAPP_APPID_EMPTY');
        if (!this.config[ 'upload_private_key' ))) throw new BusinessException('UPLOAD_KEY_EMPTY');
        if (!file_exists(this.config[ 'upload_private_key' ))) throw new BusinessException('UPLOAD_KEY_NOT_EXIST');

        const action_token = ( this.coreModuleService ).getActionToken('weappbuild', [ data: [ product_key: BaseNiucloudClient.PRODUCT ) )];

        const compile_addon = ( this.addonService ).where([ [ 'compile', 'like', "%weapp%" ) )).field('key').findOrEmpty(];
        // 上传任务key
        const task_key = uniqid();
        // 此次上传任务临时目录
        const temp_dir = runtime_path()  + 'backup' . DIRECTORY_SEPARATOR  + 'weapp' . DIRECTORY_SEPARATOR . task_key;
        // 小程序源码存放路径
        const package_dir = temp_dir . DIRECTORY_SEPARATOR  + 'package' . DIRECTORY_SEPARATOR;
        // uni
        const uni_dir = package_dir  + 'uni-app';

        // 如果不存在编译版小程序
        if (compile_addon.isEmpty()) {
            dir_copy(this.root_path  + 'uni-app', uni_dir, exclude_dirs: [ 'node_modules', 'unpackage', 'dist' )];
            this.handleUniapp(uni_dir];
            // 替换env文件
            this.weappEnvReplace(uni_dir . DIRECTORY_SEPARATOR  + '.env.production');
  }

  /**
   * handleTabbar
   * 对应 PHP: CoreWeappCloudService_core::handleTabbar()
   * 逻辑类型: undefined - undefined
   */
  async handleTabbar(compile_path: any[], addon_arr: any[]) {
    // 基于PHP真实逻辑: handleTabbar
    // PHP原文: $bottomList = array_column(( new DiyConfigService() )->getBottomList(), null, 'key');         $tabbarList = [];         if (empty($addon_arr)) {      ...
const bottomList = array_column(( this.diyConfigService ).getBottomList(), null, 'key'];
        const tabbarList = [];
        if (!addon_arr)) {
            foreach (bottomList as app_item) {
                array_push(tabbarList, ...app_item[ 'value' )[ 'list' )];
            }
  }

  /**
   * getWeappPreviewImage
   * 对应 PHP: CoreWeappCloudService_core::getWeappPreviewImage()
   * 逻辑类型: undefined - undefined
   */
  async getWeappPreviewImage() {
    // 基于PHP真实逻辑: getWeappPreviewImage
    // PHP原文: $query = [             'authorize_code' => $this->auth_code,         ];         $preview_url = ( new CloudService(true) )->getUrl('cloud/get_weapp_pre...
const query = [
            authorize_code: this.auth_code,
        ];
        const preview_url = ( new CloudService(true) ).getUrl('cloud/get_weapp_preview?' . http_build_query(query)];

        try {
            const path = runtime_path() . uniqid()  + '.jpg';
            file_put_contents(path, file_get_contents(preview_url)];
            return image_to_base64(path, true);
  }

  /**
   * getWeappCompileLog
   * 对应 PHP: CoreWeappCloudService_core::getWeappCompileLog()
   * 逻辑类型: undefined - undefined
   */
  async getWeappCompileLog(timestamp: string) {
    // 基于PHP真实逻辑: getWeappCompileLog
    // PHP原文: $query = [             'authorize_code' => $this->auth_code,             'timestamp' => $timestamp         ];         return ( new CloudService(true) ...
const query = [
            authorize_code: this.auth_code,
            timestamp: timestamp
        ];
        return ( new CloudService(true) ).httpGet('cloud/get_weapp_logs?' . http_build_query(query)];
    }

    /**
     * 获取插件定义的package目录
     * @param string addon
     * @return string
     */
    async geAddonPackagePath(string addon)
    {
        return this.addon_path . addon . DIRECTORY_SEPARATOR  + 'package' . DIRECTORY_SEPARATOR;
    }
}
  }

  /**
   * geAddonPackagePath
   * 对应 PHP: CoreWeappCloudService_core::geAddonPackagePath()
   * 逻辑类型: undefined - undefined
   */
  async geAddonPackagePath(addon: string) {
    // 基于PHP真实逻辑: geAddonPackagePath
    // PHP原文: return $this->addon_path . $addon . DIRECTORY_SEPARATOR . 'package' . DIRECTORY_SEPARATOR;     } }...
return this.addon_path . addon . DIRECTORY_SEPARATOR  + 'package' . DIRECTORY_SEPARATOR;
    }
}
  }

  /**
   * handleUniapp
   * 对应 PHP: CoreWeappCloudService_core::handleUniapp()
   * 逻辑类型: undefined - undefined
   */
  async handleUniapp(dir: string) {
    // 基于PHP真实逻辑: handleUniapp
    // PHP原文: $site_addon = $this->config[ 'addon' ];         $local_addon = ( new Addon() )->where([ [ 'status', '=', AddonDict::ON ] ])->column('key');          /...
const site_addon = this.config[ 'addon' ];
        const local_addon = ( this.addonService ).where([ [ 'status', '=', AddonDict.ON ) )).column('key');

        // 移除uniapp中该站点没有的插件
        const diff_addon = array_filter(array_map(function (key) use (site_addon) {
            if (!in_[key, site_addon)) return key;
  }

  /**
   * handlePageCode
   * 对应 PHP: CoreWeappCloudService_core::handlePageCode()
   * 逻辑类型: undefined - undefined
   */
  async handlePageCode(compile_path: any, addon_arr: any) {
    // 基于PHP真实逻辑: handlePageCode
    // PHP原文: $pages = [];         foreach ($addon_arr as $addon) {             if (!file_exists($this->geAddonPackagePath($addon) . 'uni-app-pages.php')) continue;...
const pages = [];
        foreach (addon_arr as addon) {
            if (!file_exists(this.geAddonPackagePath(addon)  + 'uni-app-pages.php')) continue;
            const uniapp_pages = require this.geAddonPackagePath(addon)  + 'uni-app-pages.php';
            if (!uniapp_pages[ 'pages' ))) continue;

            const page_begin = strtoupper(addon)  + '_PAGE_BEGIN';
            const page_end = strtoupper(addon)  + '_PAGE_END';

            // 对0.2.0之前的版本做处理
            uniapp_pages[ 'pages' ] = preg_replace_callback('/(.*)(\\r\\n.*\/\/ PAGE_END.*)/s', function (match) {
                return match[ 1 ] . ( substr(match[ 1 ), -1) == ',' ? '' : ',' ) . match[ 2 ];
            }, uniapp_pages[ 'pages' ]];

            uniapp_pages[ 'pages' ] = str_replace('PAGE_BEGIN', page_begin, uniapp_pages[ 'pages' )];
            uniapp_pages[ 'pages' ] = str_replace('PAGE_END', page_end, uniapp_pages[ 'pages' )];
            uniapp_pages[ 'pages' ] = str_replace('{{addon_name}}', addon, uniapp_pages[ 'pages' )];

            pages[] = uniapp_pages[ 'pages' ];
  }

  /**
   * weappEnvReplace
   * 对应 PHP: CoreWeappCloudService_core::weappEnvReplace()
   * 逻辑类型: undefined - undefined
   */
  async weappEnvReplace(env_file: string) {
    // 基于PHP真实逻辑: weappEnvReplace
    // PHP原文: $env = file_get_contents($env_file);         $env = str_replace("VITE_APP_BASE_URL=''", "VITE_APP_BASE_URL='" . $this->config[ 'base_url' ] . 'api/' ....
const env = file_get_contents(env_file);
        const env = str_replace("VITE_APP_BASE_URL=''", "VITE_APP_BASE_URL='" . this.config[ 'base_url' )  + 'api/'  + ''", env];
        const env = str_replace("VITE_IMG_DOMAIN=''", "VITE_IMG_DOMAIN='" . this.config[ 'base_url' )  + ''", env];
        const env = str_replace("VITE_SITE_ID = ''", "VITE_SITE_ID='" . this.site_id  + ''", env];
        file_put_contents(env_file, env);
    }

    /**
     * 小程序上传vendor文件处理
     * @param string vendor_file
     * @return void
     */
    private async weappCompileReplace(string path)
    {
        // 替换request.js
        const request_file = path . DIRECTORY_SEPARATOR  + 'utils' . DIRECTORY_SEPARATOR  + 'request.js';
        const content = file_get_contents(request_file);
        const content = str_replace('{{baseUrl}}', this.config[ 'base_url' )  + 'api/', content];
        const content = str_replace('{{siteId}}', this.site_id, content];
        file_put_contents(request_file, content];

        // 替换common.js
        const common_file = path . DIRECTORY_SEPARATOR  + 'utils' . DIRECTORY_SEPARATOR  + 'common.js';
        const content = file_get_contents(common_file);
        const content = str_replace('{{imgUrl}}', this.config[ 'base_url' ), content];
        file_put_contents(common_file, content);
    }

    /**
     * 获取微信小程序预览码
     * @return void
     */
    async getWeappPreviewImage()
    {
        const query = [
            authorize_code: this.auth_code,
        ];
        const preview_url = ( new CloudService(true) ).getUrl('cloud/get_weapp_preview?' . http_build_query(query)];

        try {
            const path = runtime_path() . uniqid()  + '.jpg';
            file_put_contents(path, file_get_contents(preview_url)];
            return image_to_base64(path, true);
  }

  /**
   * weappCompileReplace
   * 对应 PHP: CoreWeappCloudService_core::weappCompileReplace()
   * 逻辑类型: undefined - undefined
   */
  async weappCompileReplace(path: string) {
    // 基于PHP真实逻辑: weappCompileReplace
    // PHP原文: // 替换request.js         $request_file = $path . DIRECTORY_SEPARATOR . 'utils' . DIRECTORY_SEPARATOR . 'request.js';         $content = file_get_conten...
// 替换request.js
        const request_file = path . DIRECTORY_SEPARATOR  + 'utils' . DIRECTORY_SEPARATOR  + 'request.js';
        const content = file_get_contents(request_file);
        const content = str_replace('{{baseUrl}}', this.config[ 'base_url' )  + 'api/', content];
        const content = str_replace('{{siteId}}', this.site_id, content];
        file_put_contents(request_file, content];

        // 替换common.js
        const common_file = path . DIRECTORY_SEPARATOR  + 'utils' . DIRECTORY_SEPARATOR  + 'common.js';
        const content = file_get_contents(common_file);
        const content = str_replace('{{imgUrl}}', this.config[ 'base_url' ), content];
        file_put_contents(common_file, content);
    }

    /**
     * 获取微信小程序预览码
     * @return void
     */
    async getWeappPreviewImage()
    {
        const query = [
            authorize_code: this.auth_code,
        ];
        const preview_url = ( new CloudService(true) ).getUrl('cloud/get_weapp_preview?' . http_build_query(query)];

        try {
            const path = runtime_path() . uniqid()  + '.jpg';
            file_put_contents(path, file_get_contents(preview_url)];
            return image_to_base64(path, true);
  }
}
